from threading import Thread
from GetHostIP import HostIP
import socket


def rec_data(udpSocket):
    while True:
        rec_info = udpSocket.recvfrom(1024)
        print("\r>>%s:%s" % (rec_info[1], rec_info[0].decode("gb2312")))
        print("<<", end="")


def send_data(udpSocket, ip, port):
    while True:
        addr = (ip, port)
        send_msg = input("<<")
        udpSocket.sendto(send_msg.encode("gb2312"), addr)


def main():
    # ip = input("ip:")
    ip = HostIP().ip
    # ip = '127.0.0.1'
    port = int(input("port:"))
    udpSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udpSocket.bind(("", 8800))
    tr = Thread(target=rec_data, args=[udpSocket])
    ts = Thread(target=send_data, args=[udpSocket, ip, port])
    tr.start()
    ts.start()
    tr.join()
    ts.join()


if __name__ == '__main__':
    main()
